/*
 * @Author: jiaxiuc
 * @Date: 2024-02-29 15:53:15
 * @LastEditors: 503906670@qq.com
 * @LastEditTime: 2024-03-06 20:03:04
 */
/************************************/
/***********************************/
export default async (url = '', { data = {}, type = 'POST', method = 'ajax' } = {}) => {
    type = type.toUpperCase();
    //url = baseUrl+url;
    let dataStr = $.param(data); //数据拼接字符串
    if (type == 'GET' && dataStr !== '') {
        if (url.indexOf('?') != -1) {
            url = url + '&' + dataStr;
        } else {
            url = url + '?' + dataStr;
        }
    }
    if (window.fetch && method == 'fetch') {
        let requestConfig = {
            //credentials: 'include',
            method: type,
            /*headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},*/
            mode: 'cors',
            cache: 'force-cache'
        };
        if (type == 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            });
        }
        try {
            const response = await fetch(url, requestConfig);
            const responseJson = await response.json().then(function (res) {
                return res;
            });
            return responseJson;
        } catch (error) {
            throw new Error(error);
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject();
            }
            requestObj.open(type, url, true);
            requestObj.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            requestObj.send(dataStr);
            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response;
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj);
                    } else {
                        reject(requestObj);
                    }
                }
            };
        }).catch(e=>{
           
        });
    }
};
